import json
import requests
from PIL import Image
from io import BytesIO

class WxCode(object):
    def __init__(self, appID, appSecret):
        self.appID = appID;
        self.appSecret = appSecret
        self.token_url = 'https://api.weixin.qq.com/cgi-bin/token'
        self.token = None
        # # 菊花式
        # self.code_url_circle = 'https://api.weixin.qq.com/wxa/getwxacode'
        # # 狗皮膏药式
        # self.code_url_rect = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode'
        # 无限制借口
        self.code_url_unlimit = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit'
    
    def get_access_token(self):
        url = '%s?grant_type=client_credential&appid=%s&secret=%s' % (self.token_url, self.appID, self.appSecret)
        x = requests.get(url)
        if x.ok:
            jo = x.json()
            self.token = jo['access_token']
            return True
        else:
            return False
    
    def get_code(self, filepath, page, param_str, width):
        # url = '%s?access_token=%s' % (self.code_url_circle if code_type == 0 else self.code_url_rect, self.token)
        url = '%s?access_token=%s' % (self.code_url_unlimit, self.token)
        data = {
            'path': page,
            'width': width,
            'scene': param_str
        }
        x = requests.post(url, data=json.dumps(data).encode(encoding='utf-8'), headers={'Content-Type': 'application/json'})
        # x = requests.post(url, data=data)
        print(x.status_code)
        if x.ok:
            img = Image.open(BytesIO(x.content))
            img.save(filepath)

if __name__ == '__main__':
    obj = WxCode('wx6e595ae50c27572c', '520408a7d595a2a524a0592e461463f4')
    if obj.get_access_token():
        obj.get_code('/tmp/wxcode.png', 'pages/map/map', '2', 1280)

